import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { Restaurant } from '../../entities/restaurant.entity';
import {
  CreateRestaurantDto,
  UpdateRestaurantDto,
  QueryRestaurantDto,
} from './dto';
import { PaginatedResponse } from '../../common/interfaces/api-response.interface';

@Injectable()
export class RestaurantService {
  constructor(
    @InjectRepository(Restaurant)
    private readonly restaurantRepository: Repository<Restaurant>,
  ) {}

  // 获取餐厅列表（分页）
  async getRestaurants(
    query: QueryRestaurantDto,
  ): Promise<PaginatedResponse<Restaurant>> {
    const { page = 1, pageSize = 10, category, search } = query;
    const skip = (page - 1) * pageSize;

    const queryBuilder =
      this.restaurantRepository.createQueryBuilder('restaurant');

    if (category) {
      queryBuilder.andWhere('restaurant.category = :category', { category });
    }

    if (search) {
      queryBuilder.andWhere(
        '(restaurant.name LIKE :search OR restaurant.notes LIKE :search)',
        { search: `%${search}%` },
      );
    }

    queryBuilder
      .orderBy('restaurant.created_at', 'DESC')
      .skip(skip)
      .take(pageSize);

    const [data, total] = await queryBuilder.getManyAndCount();
    const totalPages = Math.ceil(total / pageSize);

    return {
      data,
      total,
      page,
      pageSize,
      totalPages,
    };
  }

  // 获取所有餐厅
  async getAllRestaurants(): Promise<Restaurant[]> {
    return this.restaurantRepository.find({
      order: { created_at: 'DESC' },
    });
  }

  // 根据ID获取餐厅
  async getRestaurantById(id: string): Promise<Restaurant> {
    const restaurant = await this.restaurantRepository.findOne({
      where: { id },
    });

    if (!restaurant) {
      throw new NotFoundException(`餐厅 ID ${id} 不存在`);
    }

    return restaurant;
  }

  // 创建餐厅
  async createRestaurant(
    createRestaurantDto: CreateRestaurantDto,
  ): Promise<Restaurant> {
    const restaurant = this.restaurantRepository.create(createRestaurantDto);
    return this.restaurantRepository.save(restaurant);
  }

  // 更新餐厅
  async updateRestaurant(
    id: string,
    updateRestaurantDto: UpdateRestaurantDto,
  ): Promise<Restaurant> {
    const restaurant = await this.getRestaurantById(id);

    Object.assign(restaurant, updateRestaurantDto);
    return this.restaurantRepository.save(restaurant);
  }

  // 删除餐厅
  async deleteRestaurant(id: string): Promise<void> {
    const restaurant = await this.getRestaurantById(id);
    await this.restaurantRepository.remove(restaurant);
  }

  // 批量删除餐厅
  async batchDeleteRestaurants(ids: string[]): Promise<void> {
    await this.restaurantRepository.delete(ids);
  }

  // 获取餐厅分类列表
  async getCategories(): Promise<string[]> {
    const result = await this.restaurantRepository
      .createQueryBuilder('restaurant')
      .select('DISTINCT restaurant.category', 'category')
      .getRawMany();

    return result.map((item: { category: string }) => item.category);
  }

  // 获取频率规则列表
  getFrequencyRules(): string[] {
    return ['daily', 'weekly', 'monthly'];
  }

  // 搜索餐厅
  async searchRestaurants(keyword: string): Promise<Restaurant[]> {
    return this.restaurantRepository.find({
      where: [{ name: Like(`%${keyword}%`) }, { notes: Like(`%${keyword}%`) }],
      order: { created_at: 'DESC' },
    });
  }
}
